package wekan.client;

import android.location.Location;
import android.util.Log;

import java.io.*;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Created with IntelliJ IDEA.
 * User: nitneuq65
 * Date: 07/08/12
 * Time: 12:39
 * To change this template use File | Settings | File Templates.
 */
public class WNetwork extends Thread {
    private Socket client;
    private DataInputStream input;
    private DataOutputStream output;
    private boolean connected;
    private Location locationBuff;
    private boolean sendingLocation;

    public WNetwork(){
        super();
        connected=false;
        input=null;
        output=null;
        locationBuff=null;
        sendingLocation=false;
    }

    public void run(){
        try {
            Log.d(WModel.TAG, "NETWORK STARTING ...") ;
            client = new Socket("10.0.2.2",5000);
            if(client.isConnected()){
                input = new DataInputStream(client.getInputStream());
                output = new DataOutputStream(client.getOutputStream());

                while(true){
                    synchronized (this){
                        wait(500);
                    }
                    if(sendingLocation){
                        writeLoc(locationBuff);
                        sendingLocation=false;
                        locationBuff=null;
                    }

                    if(input.available()>0){

                    }
                }
            }



        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public synchronized void send(Location l){
        sendingLocation=true;
        locationBuff=l;
    }


    private void writeLoc(Location l) throws IOException {
        long lon = Double.doubleToLongBits(l.getLongitude());
        long lat = Double.doubleToLongBits(l.getLatitude());

        int[] lonBuff = new int[8];
        int[] latBuff = new int[8];

        for(int i=0; i<8; i++){
            lonBuff[i]= (int) ((lon & (long)(0xFF<<i))>>i);
            latBuff[i]= (int) ((lat & (long)(0xFF<<i))>>i);
        }

        for(int i=0; i<8; i++)
            output.write(latBuff[i]);

        for(int i=0; i<8; i++)
            output.write(lonBuff[i]);
    }



    public synchronized void stopNetwork() throws Throwable {
        output.close();
        input.close();
        client.close();
        this.finalize();
    }



    public synchronized boolean isConnected(){
        return connected;
    }



}
